package com.zscat.mallplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.center.entity.CenterVerification;
import com.zscat.mallplus.center.mapper.CenterVerificationMapper;
import com.zscat.mallplus.center.service.ICenterItemService;
import com.zscat.mallplus.center.service.ICenterJifenService;
import com.zscat.mallplus.center.service.ICenterOrderService;
import com.zscat.mallplus.enums.AllEnum;
import com.zscat.mallplus.enums.AllEnum.OrderType;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.exception.ApiMallPlusException;
import com.zscat.mallplus.oms.entity.*;
import com.zscat.mallplus.oms.mapper.OmsOrderItemMapper;
import com.zscat.mallplus.oms.mapper.OmsOrderSettingMapper;
import com.zscat.mallplus.oms.service.*;
import com.zscat.mallplus.oms.vo.PayParam;
import com.zscat.mallplus.sms.entity.SmsGroup;
import com.zscat.mallplus.sms.entity.SmsGroupMember;
import com.zscat.mallplus.sms.entity.SmsGroupRecord;
import com.zscat.mallplus.sms.mapper.SmsGroupMapper;
import com.zscat.mallplus.sms.mapper.SmsGroupRecordMapper;
import com.zscat.mallplus.sms.service.ISmsGroupMemberService;
import com.zscat.mallplus.sms.service.ISmsGroupService;
import com.zscat.mallplus.sys.entity.SysSystemSetting;
import com.zscat.mallplus.sys.mapper.SysSystemSettingMapper;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.mapper.SysAppletSetMapper;
import com.zscat.mallplus.ums.service.IUmsMemberBlanceLogService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.util.*;
import com.zscat.mallplus.util.applet.WechatRefundApiResult;
import com.zscat.mallplus.util.applet.WechatUtil;
import com.zscat.mallplus.utils.CommonResult;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;

/**
 * 作者: @author mallplus <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "商户支付 统一用com.zscat.mallplus.pay.controller")
@Slf4j
@RestController
@RequestMapping("/api/pay")
public class PayController extends ApiBaseAction {
	private static Logger LOGGER = LoggerFactory.getLogger(PayController.class);
	String tradeType = "JSAPI";
	String uniformorder = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	String orderquery = "https://api.mch.weixin.qq.com/pay/orderquery";
	String refundUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";
	String refundqueryUrl = "https://api.mch.weixin.qq.com/pay/refundquery";
	@Autowired
	private IOmsPaymentsService paymentsService;
	@Resource
	private SysAppletSetMapper appletSetMapper;
	@Resource
	private IOmsOrderService orderService;
	@Resource
	private IUmsMemberService memberService;
	@Resource
	private IUmsMemberBlanceLogService blanceLogService;
	@Resource
	private IOmsOrderItemService orderItemService;
	@Resource
	private SmsGroupMapper groupMapper;
	@Autowired
	private IOmsOrderOperateHistoryService orderOperateHistoryService;

	@Resource
	private SysSystemSettingMapper settingMapper;

	@Resource
	private IOmsOrderItemTicketService orderItemTicketService;

	@Resource
	private CenterVerificationMapper verificationMapper;
	@Resource
	private OmsOrderItemMapper orderItemMapper;
	@Resource
	private ISmsGroupMemberService groupMemberService;
	@Resource
	private SmsGroupRecordMapper groupRecordMapper;
	@Resource
	private ISmsGroupService groupService;
	@Resource
	private OmsOrderSettingMapper orderSettingMapper;
	@Resource
	private ICenterJifenService centerService;
	@Resource
	private ICenterItemService centerItemService;
	@Autowired
	private ICenterOrderService centerOrderService;

	/**
	 * 订单退款请求
	 */
	/*
	 * @SysLog(MODULE = "pay", REMARK = "订单退款请求")
	 * 
	 * @ApiOperation(value = "订单退款请求")
	 * 
	 * @PostMapping("refund") public Object refund(Integer orderId) { // OrderVo
	 * orderInfo = orderService.queryObject(orderId);
	 * 
	 * if (null == orderInfo) { return toResponsObject(400, "订单已取消", ""); }
	 * 
	 * if (orderInfo.getOrder_status() == 401 || orderInfo.getOrder_status() == 402)
	 * { return toResponsObject(400, "订单已退款", ""); }
	 * 
	 * WechatRefundApiResult result =
	 * WechatUtil.wxRefund(orderInfo.getId().toString(), 10.01, 10.01); if
	 * (result.getResult_code().equals("SUCCESS")) { if (orderInfo.getOrder_status()
	 * == 201) { orderInfo.setOrder_status(401); } else if
	 * (orderInfo.getOrder_status() == 300) { orderInfo.setOrder_status(402); }
	 * orderService.updateAll(orderInfo); return toResponsObject(400, "成功退款", ""); }
	 * else { return toResponsObject(400, "退款失败", ""); } }
	 */

	// 返回微信服务
	public static String setXml(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}

	// 模拟微信回调接口
	public static String callbakcXml(String orderNum) {
		return "<xml><appid><![CDATA[wx2421b1c4370ec43b]]></appid><attach><![CDATA[支付测试]]></attach><bank_type><![CDATA[CFT]]></bank_type><fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[10000100]]></mch_id><nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str><openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid> <out_trade_no><![CDATA["
				+ orderNum
				+ "]]></out_trade_no>  <result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign><sub_mch_id><![CDATA[10000100]]></sub_mch_id> <time_end><![CDATA[20140903131540]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id></xml>";
	}

	@IgnoreAuth
	@ApiOperation("显示所有支付方式")
	@RequestMapping(value = "/paymentlist", method = RequestMethod.GET)
	public Object getPayments() {
		List<OmsPayments> paymentss = paymentsService.list(new QueryWrapper<OmsPayments>().eq("status", 1));
		return new CommonResult().success(paymentss);
	}

	/**
	 * 余额支付
	 */
	@SysLog(MODULE = "pay", REMARK = "余额支付")
	@ApiOperation(value = "余额支付")
	@PostMapping("allPay")
	public Object allPay(@ApiParam(value = "额余支付参数") @RequestBody PayParam payParam) {
		try {
			Object order = orderService.blancePay(orderService.getById(payParam.getOrderId()));
			return new CommonResult().success(order);
		} catch (Exception e) {
			return new CommonResult().failed(e.getMessage());
		}

	}

	/**
	 * 余额支付
	 */
	@SysLog(MODULE = "pay", REMARK = "余额支付")
	@ApiOperation(value = "余额支付")
	@PostMapping("balancePay")
	public Object balancePay(@ApiParam(value = "额余支付参数") PayParam payParam) {

		try {
			Object order = orderService.blancePay(payParam);
			return new CommonResult().success(order);
		} catch (Exception e) {
			return new CommonResult().failed(e.getMessage());
		}
	}

	/**
	 * 获取支付的请求参数
	 */
	@SysLog(MODULE = "pay", REMARK = "获取支付的请求参数")
	@ApiOperation(value = "获取支付的请求参数")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderId", value = "订单编号", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "appIdsource", value = "appId的来源", required = false, dataType = "int", paramType = "query", defaultValue = "2") })
	@PostMapping("weixinAppletPay")
	public Object payPrepay(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId,
			@RequestParam(value = "appIdsource", required = false) Integer appIdsource) {
		UmsMember user = memberService.getNewCurrentMember();
		OmsOrder orderInfo = orderService.getById(orderId);
		OmsPayments appletSet = memberService.getSysAppletSet(appIdsource);
		if (null == appletSet) {
			throw new ApiMallPlusException("没有设置支付配置");
		}

		if (null == orderInfo) {
			return toResponsObject(400, "订单已取消", "");
		}

		if (orderInfo.getStatus() == OrderStatus.CLOSED.getValue()) {
			return toResponsObject(400, "订单已已关闭，请不要重复操作", "");
		}
		// 秒杀库存判断
		if (orderInfo.getOrderType() == OrderType.SKILL.code()) {
			OmsOrderItem orderItem = orderItemService
					.getOne(new QueryWrapper<OmsOrderItem>().eq("order_id", orderInfo.getId()));
			boolean flag = centerOrderService.judgeFlashPromotionLimit(user.getId(), orderItem.getActId(),0);
			if (!flag) {
				return toResponsObject(400, "秒杀库存不足", "");
			}
		}

		String nonceStr = CharUtil.getRandomString(32);
		SysSystemSetting setting = settingMapper.selectById(1);
		String notifyUrl = setting.getSiteUrl().concat("/api/pay/notify");
		// https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
		Map<Object, Object> resultObj = new TreeMap();

		try {
			Map<Object, Object> parame = new TreeMap<Object, Object>();
			// 小程序ID
			parame.put("appid", appletSet.getAppId());
			// 商户号
			parame.put("mch_id", appletSet.getMchId());
			// 生成随机字符串
			String randomStr = CharUtil.getRandomNum(18).toUpperCase();
			// 随机字符串
			parame.put("nonce_str", randomStr);
			// 商户订单号
			parame.put("out_trade_no", orderInfo.getOrderSn());
			// 商品描述
			parame.put("body", "超市-支付");
			// 支付金额
			parame.put("total_fee", orderInfo.getPayAmount().multiply(new BigDecimal(100)).intValue());
			// 回调地址
			parame.put("notify_url", notifyUrl);
			// 交易类型APP
			parame.put("trade_type", tradeType);
			parame.put("spbill_create_ip", getClientIp());
			parame.put("openid", user.getWeixinOpenid());
			String sign = WechatUtil.arraySign(parame, appletSet.getPartnerKey());
			// 数字签证
			parame.put("sign", sign);

			String xml = MapUtils.convertMap2Xml(parame);
			log.info("xml:" + xml);
			Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
			// 响应报文
			String return_code = MapUtils.getString("return_code", resultUn);
			String return_msg = MapUtils.getString("return_msg", resultUn);
			//
			if (return_code.equalsIgnoreCase("FAIL")) {
				return new CommonResult().failed("支付失败," + return_msg);
			} else if (return_code.equalsIgnoreCase("SUCCESS")) {
				// 返回数据
				String result_code = MapUtils.getString("result_code", resultUn);
				String err_code_des = MapUtils.getString("err_code_des", resultUn);
				if (result_code.equalsIgnoreCase("FAIL")) {
					return new CommonResult().failed("支付失败," + err_code_des);
				} else if (result_code.equalsIgnoreCase("SUCCESS")) {
					String prepay_id = MapUtils.getString("prepay_id", resultUn);
					// 先生成paySign
					// 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
					resultObj.put("appId", appletSet.getAppId());
					resultObj.put("timeStamp",
							DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
					resultObj.put("nonceStr", nonceStr);
					resultObj.put("package", "prepay_id=" + prepay_id);
					resultObj.put("signType", "MD5");
					String paySign = WechatUtil.arraySign(resultObj, appletSet.getPartnerKey());
					resultObj.put("paySign", paySign);
					// 业务处理
					orderInfo.setPrepayId(prepay_id);
					// 付款中
					orderInfo.setStatus(OrderStatus.INIT.getValue());
					orderInfo.setPaymentTime(new Date());
					orderInfo.setModifyTime(new Date());
					orderService.updateById(orderInfo);

					if (orderInfo.getPid() == null) {
						OmsOrder neworder = new OmsOrder();
						orderInfo.setStatus(OrderStatus.INIT.getValue());
						neworder.setPayType(AllEnum.OrderPayType.weixinAppletPay.code());
						neworder.setPaymentTime(new Date());
						neworder.setModifyTime(new Date());
						orderService.update(neworder, new QueryWrapper<OmsOrder>().eq("pid", orderInfo.getId()));
					}
					return toResponsObject(200, "微信统一订单下单成功", resultObj);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new CommonResult().failed("支付失败,error=" + e.getMessage());
		}
		return new CommonResult().failed("支付失败");
	}

	/**
	 * 微信查询订单状态
	 */
	@SysLog(MODULE = "pay", REMARK = "查询订单状态")
	@ApiOperation(value = "查询订单状态")
	@GetMapping("query")
	public Object orderQuery(@RequestParam(value = "id", required = false, defaultValue = "0") Long id,
			@RequestParam(value = "appIdsource", required = false) Integer appIdsource) {
		UmsMember user = memberService.getNewCurrentMember();
		OmsPayments appletSet = memberService.getSysAppletSet(appIdsource);
		if (null == appletSet) {
			throw new ApiMallPlusException("没有设置支付配置");
		}
		OmsOrder orderDetail = orderService.getById(id);
		if (id == null) {
			throw new ApiMallPlusException("订单不存在");
		}
		Map<Object, Object> parame = new TreeMap<Object, Object>();
		// 微信分配的小程序ID
		parame.put("appid", appletSet.getAppId());
		// 微信支付分配的商户号
		parame.put("mch_id", appletSet.getMchId());
		// 生成随机字符串
		String randomStr = CharUtil.getRandomNum(18).toUpperCase();
		// 随机字符串
		parame.put("nonce_str", randomStr);
		// 商户订单号
		parame.put("out_trade_no", orderDetail.getOrderSn());

		String sign = WechatUtil.arraySign(parame, appletSet.getPartnerKey());
		// 数字签证
		parame.put("sign", sign);

		String xml = MapUtils.convertMap2Xml(parame);
		log.info("xml:" + xml);
		Map<String, Object> resultUn = null;
		try {
			resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(orderquery, xml));
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApiMallPlusException("查询失败,error=" + e.getMessage());
		}
		// 响应报文
		String return_code = MapUtils.getString("return_code", resultUn);
		String return_msg = MapUtils.getString("return_msg", resultUn);

		if (!"SUCCESS".equals(return_code)) {
			throw new ApiMallPlusException("查询失败,error=" + return_msg);
		}

		String trade_state = MapUtils.getString("trade_state", resultUn);
		if ("SUCCESS".equals(trade_state)) {
			// 更改订单状态
			// 业务处理
			OmsOrder orderInfo = new OmsOrder();
			orderInfo.setId(id);
			orderInfo.setStatus(OrderStatus.TO_DELIVER.getValue());
			orderInfo.setConfirmStatus(1);
			orderInfo.setPaymentTime(new Date());
			orderInfo.setModifyTime(new Date());
			orderService.updateById(orderInfo);
			return new CommonResult().success("支付成功");
		} else if ("USERPAYING".equals(trade_state)) {
			// 重新查询 正在支付中
			/*
			 * Integer num = (Integer) J2CacheUtils.get(J2CacheUtils.SHOP_CACHE_NAME,
			 * "queryRepeatNum" + id + ""); if (num == null) {
			 * J2CacheUtils.put(J2CacheUtils.SHOP_CACHE_NAME, "queryRepeatNum" + id + "",
			 * 1); this.orderQuery(id); } else if (num <= 3) {
			 * J2CacheUtils.remove(J2CacheUtils.SHOP_CACHE_NAME, "queryRepeatNum" + id);
			 * this.orderQuery(id); } else { throw new ApiMallPlusException("查询失败,error=" +
			 * trade_state); }
			 */

		} else {
			// 失败
			throw new ApiMallPlusException("查询失败,error=" + trade_state);
		}

		throw new ApiMallPlusException("查询失败，未知错误");
	}

	/**
	 * 微信订单回调接口
	 *
	 * @return
	 */
	@SysLog(MODULE = "pay", REMARK = "微信订单回调接口")
	@ApiOperation(value = "微信订单回调接口")
	@RequestMapping(value = "notify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public void notify(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("==============================开始回调================================");
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			InputStream in = request.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.close();
			in.close();
			// xml数据
			String reponseXml = new String(out.toByteArray(), "utf-8");

			WechatRefundApiResult result = (WechatRefundApiResult) XmlUtil.xmlStrToBean(reponseXml,
					WechatRefundApiResult.class);
			String result_code = result.getResult_code();
			// 订单编号
			String out_trade_no = result.getOut_trade_no();
			log.info("订单" + out_trade_no + "支付成功");
			// 业务处理
			OmsOrder param = new OmsOrder();
			param.setOrderSn(out_trade_no);
			List<OmsOrder> list = orderService.list(new QueryWrapper<>(param));
			OmsOrder order = list.get(0);
			order.setStatus(OrderStatus.TO_DELIVER.getValue());
			order.setPaymentTime(new Date());
			// 根据订单ID查询订单商品清单
			List<OmsOrderItem> orderItems = orderItemService
					.list(new QueryWrapper<OmsOrderItem>().eq("order_id", order.getId()));
			if (result_code.equalsIgnoreCase("FAIL")) {
				log.error("订单" + out_trade_no + "支付失败");
				orderService.releaseStock(order);
				response.getWriter().write(setXml("SUCCESS", "OK"));
			} else if (result_code.equalsIgnoreCase("SUCCESS")) { // 支付成功
				// 根据下单用户ID查询用户信息
				UmsMember currentMember = memberService.getById(order.getMemberId());
				order.setPayType(AllEnum.OrderPayType.weixinAppletPay.code());
				boolean groupFlag = false;
				if (order.getOrderType() == OrderType.PIN_GROUP.code()) {
					order.setStatus(OrderStatus.PINTUAN_ORDER.getValue());
					SmsGroupMember groupMember = groupMemberService
							.getOne(new QueryWrapper<SmsGroupMember>().eq("order_id", order.getId()));
					groupMember.setStatus(2);// 状态：支付成功
					groupMemberService.updateById(groupMember);

					SmsGroup group = groupService.getById(groupMember.getGroupId());
					List<SmsGroupMember> groupMemberList = groupMemberService
							.list(new QueryWrapper<SmsGroupMember>().eq("group_id", groupMember.getGroupId())
									.eq("group_record_id", groupMember.getGroupRecordId()).eq("status", 2));
					SmsGroupRecord groupRecord = groupRecordMapper.selectById(groupMember.getGroupRecordId());

					// 开团时间
					if (null == groupRecord.getBeginTime()) {
						groupRecord.setBeginTime(new Date());
						OmsOrderSetting orderSetting = orderSettingMapper.selectOne(new QueryWrapper<>());
						Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GTM+8"));
						calendar.setTime(groupRecord.getBeginTime());
						calendar.add(Calendar.HOUR_OF_DAY, orderSetting.getGroupOrderOvertime());
						groupRecord.setEndTime(group.getEndTime().compareTo(calendar.getTime()) > 0 ? calendar.getTime()
								: group.getEndTime());
					}
					for (OmsOrderItem orderItem : orderItems) {
						orderItem.setEndTime(groupRecord.getEndTime());
						orderItemService.updateById(orderItem);
					}
					if (groupMemberList != null && groupMemberList.size() == group.getMaxPeople()) {
						groupRecord.setStatus("2");// 拼团成功
						groupRecordMapper.updateById(groupRecord);
						groupFlag = true;
						order.setStatus(OrderStatus.TO_DELIVER.getValue());
						for (OmsOrderItem orderItem : orderItems) {
							if (orderItem.getType() == 2) {
								generateGroupOrderTicket(orderItem, currentMember);
								order.setStatus(OrderStatus.BE_USED.getValue());
							}
						}
						memberService.addIntegration(currentMember.getId(),
								order.getPayAmount().multiply(new BigDecimal("0.1")).intValue(), 1, "小程序支付添加积分",
								AllEnum.ChangeSource.order.code(), currentMember.getUsername());

						// 分拥计算
						OmsOrderItem queryO = new OmsOrderItem();
						queryO.setOrderId(order.getId());
						queryO.setType(AllEnum.OrderItemType.GOODS.code());
						List<OmsOrderItem> orderItemList = orderItemService.list(new QueryWrapper<>(queryO));
						orderService.recordFenxiaoMoney(orderItemList, currentMember);

						// 其他拼团订单

						for (SmsGroupMember smsGroupMember : groupMemberList) {
							if (smsGroupMember.getMemberId().compareTo(groupMember.getMemberId()) != 0) {
								OmsOrder groupOrder = orderService
										.getOne(new QueryWrapper<OmsOrder>().eq("id", smsGroupMember.getOrderId()));
								groupOrder.setStatus(OrderStatus.TO_DELIVER.getValue());
								List<OmsOrderItem> groupOrderItemList = orderItemService.list(
										new QueryWrapper<OmsOrderItem>().eq("order_id", smsGroupMember.getOrderId()));
								UmsMember member = memberService.getById(groupOrder.getMemberId());
								for (OmsOrderItem orderItem : groupOrderItemList) {
									orderItem.setEndTime(groupRecord.getEndTime());
									orderItemService.updateById(orderItem);
									if (orderItem.getType() == 2) { // 虚拟商品
										generateGroupOrderTicket(orderItem, member);
										groupOrder.setStatus(OrderStatus.BE_USED.getValue());
									}
								}
								groupOrder.setModifyTime(new Date());
								orderService.updateById(groupOrder);
								// 历史记录
								OmsOrderOperateHistory orderOperateHistory = new OmsOrderOperateHistory();
								orderOperateHistory.setOrderId(groupOrder.getId());
								orderOperateHistory.setCreateTime(new Date());
								orderOperateHistory.setOperateMan(currentMember.getNickname());
								orderOperateHistory.setPreStatus(OrderStatus.PINTUAN_ORDER.getValue());
								orderOperateHistory.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
								orderOperateHistory.setNote("微信支付");
								orderOperateHistoryService.save(orderOperateHistory);
								// 送积分
								memberService.addIntegration(groupOrder.getMemberId(),
										groupOrder.getPayAmount().multiply(new BigDecimal("10")).intValue(), 1,
										"其他拼团订单添加积分", AllEnum.ChangeSource.order.code(),
										groupOrder.getMemberUsername());
								// 分拥计算
								OmsOrderItem groupQuery = new OmsOrderItem();
								groupQuery.setOrderId(groupOrder.getId());
								groupQuery.setType(AllEnum.OrderItemType.GOODS.code());
								List<OmsOrderItem> groupList = orderItemService.list(new QueryWrapper<>(groupQuery));
								orderService.recordFenxiaoMoney(groupList, member);
							}
						}
					} else {
						order.setStatus(OrderStatus.PINTUAN_ORDER.getValue());
					}
					groupRecordMapper.updateById(groupRecord);
				} else {
					for (OmsOrderItem orderItem : orderItems) {
						if (orderItem.getType() == 2) { // 虚拟商品
							generateGroupOrderTicket(orderItem, currentMember);
							// 更新订单状态为可使用
							order.setStatus(OrderStatus.BE_USED.getValue());
						}
					}
					// 送积分
					memberService.addIntegration(currentMember.getId(),
							order.getPayAmount().multiply(new BigDecimal("10")).intValue(), 1, "小程序支付添加积分",
							AllEnum.ChangeSource.order.code(), currentMember.getUsername());
				}
				order.setModifyTime(new Date());
				orderService.updateById(order);

				// 订单日志记录
				OmsOrderOperateHistory history = new OmsOrderOperateHistory();
				history.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
				if (!groupFlag) {
					history.setOrderStatus(OrderStatus.PINTUAN_ORDER.getValue());
				}
				history.setOrderId(order.getId());
				history.setCreateTime(new Date());
				history.setOperateMan(currentMember.getNickname());
				history.setPreStatus(OrderStatus.INIT.getValue());
				history.setNote("微信支付");
				orderOperateHistoryService.save(history);

				response.getWriter().write(setXml("SUCCESS", "OK"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}

	/**
	 * 生成券码
	 * 
	 * @param orderItem
	 * @param member
	 */
	private void generateGroupOrderTicket(OmsOrderItem orderItem, UmsMember member) {
		for (int i = 0; i < orderItem.getProductQuantity(); i++) {
			OmsOrderItemTicket orderItemTicket = new OmsOrderItemTicket();
			orderItemTicket.setOrderId(orderItem.getOrderId());
			orderItemTicket.setOrderItemId(orderItem.getId());
			// 生成券码
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
			orderItemTicket.setCouponCode(dateFormat.format(new Date()) + RandomUtil.getRandom(6));
			orderItemTicket.setStatus(0);
			orderItemTicket.setStoreId(orderItem.getStoreId());
			orderItemTicket.setCreateTime(new Date());
			orderItemTicketService.save(orderItemTicket);

			CenterVerification entity = new CenterVerification();
			entity.setCreateTime(new Date());
			entity.setUserId(member.getId());
			entity.setNickName(member.getNickname());
			entity.setPhone(member.getPhone());
			entity.setOrderId(orderItem.getOrderId());
			entity.setOrderSn(orderItem.getOrderSn());
			entity.setProductName(orderItem.getProductName());
			entity.setProductMoney(orderItem.getProductPrice());
			entity.setStoreId(orderItem.getStoreId());
			entity.setVerification(0);
			entity.setVerificationCode(orderItemTicket.getCouponCode());
			verificationMapper.insertCenterVerification(entity);
		}
		orderItem.setStatus(OrderStatus.BE_USED.getValue());
		orderItemService.updateById(orderItem);
	}
}
